﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class OperationLogSettingEditPage : System.Windows.Window, INavigableView<OperationLogSettingEditViewModel>
    {
        public OperationLogSettingEditViewModel ViewModel { get; }

        public OperationLogSettingEditPage(OperationLogSettingEditViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            ControlHelper.SetDirtyWindow(this);
        }

        [RelayCommand]
        private void SelectEntity()
        {
            DataEntityPage service = App.GetService<DataEntityPage>();
            if (service != null && service.ShowDialog() == true)
            {
                ViewModel.Item.TableName = string.Join(",", service.ViewModel.CheckedList);
                ViewModel.NotifyChanged();
            }
        }

        [RelayCommand]
        private void Back()
        {
            Close();
        }

        [RelayCommand]
        private async Task Save()
        {
            OperationLogSettingInfo item = ViewModel.Item;
            if (item == null)
            {
                return;
            }
            if (item.TableName.IsNullOrWhiteSpace())
            {
                Growl.ErrorGlobal("请输入 表名称/实体类全名");
                txtTableName.Focus();
                return;
            }
            if (ViewModel.IsEdit)
            {
                if (await BLLFactory<IOperationLogSettingService>.Instance.IsExistAsync((OperationLogSettingInfo s) => s.TableName == ViewModel.Item.TableName && s.Id != ViewModel.Item.Id))
                {
                    MessageDxUtil.ShowTips("指定的【表名称/实体类全名】已经存在，不能重复添加，请修改");
                    return;
                }
            }
            else
            {
                List<string> entityNameList = ViewModel.Item.TableName.ToDelimitedList<string>(",");
                if (await BLLFactory<IOperationLogSettingService>.Instance.IsExistAsync((OperationLogSettingInfo s) => entityNameList.Contains(s.TableName)))
                {
                    MessageDxUtil.ShowTips("指定的【表名称/实体类全名】已经存在，不能重复添加，请修改");
                    return;
                }
            }
            await ViewModel.Save();
            if (ViewModel.Result.Success)
            {
                Back();
            }
        }
    }
}
